package com.example.transit.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.transit.R;
import com.example.transit.adapter.CouponVPAdapter;
import com.example.transit.adapter.SearchListviewAdapter;
import com.example.transit.base.BaseActivity;
import com.example.transit.bean.CarlineInfo;
import com.example.transit.bean.HistoryBean;
import com.example.transit.bean.ServerLineInfo;
import com.example.transit.bean.StationInfo;
import com.example.transit.contentprovider.DbStationInfo;
import com.example.transit.event.SearchCarlineMssEvent;
import com.example.transit.utils.ProjectDataUtils;
import com.example.transit.utils.SPUtils;
import com.example.transit.utils.UpdataAppUtil.DownLoadUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.vp_main)
    ViewPager vpMain;
    @BindView(R.id.autocomplete_country)
    AutoCompleteTextView autoCompleteTextView;
    @BindView(R.id.main_setting)
    TextView mainSetting;
    @BindView(R.id.search_img)
    ImageView searchImg;
    @BindView(R.id.delete_text)
    ImageView deleteText;
    @BindView(R.id.search_edit_lly)
    LinearLayout searchEditLly;
    @BindView(R.id.nav)
    NavigationView navigationView;
    @BindView(R.id.activity_na)
    DrawerLayout drawerLayout;



    ListView searchListview;
    List<CarlineInfo> carlineInfoList;
    private List<HistoryBean> historyBeanList;
    private CouponVPAdapter couponVPAdapter;
    CarlineInfo carlineInfo;
    Handler handler;
    String result_lineinfo;
    String result_lineServer;//获取http://122.112.241.174:10085/Busyingni/GetLineInfos信息
    Boolean isupline = true;//是否是上行；
    Boolean hasSendResult = false;

    //重新获取服务端数据作为模糊搜索数组，暂定为一条
    ProjectDataUtils projectDataUtils;
    List<StationInfo> stationlist = new ArrayList<>();//车站信息列表

    List<StationInfo> allstationlist = new ArrayList<>();//车站信息列表
    List<List<StationInfo>> serchallstationlists = new ArrayList<>();//车站信息列表
    SearchListviewAdapter searchListviewAdapter;
    //共享参数的key
    private String spstationkey = "result_statinfo";
    private String splinekey = "result_lineserver";
    //点两次返回键退出应用
    private long exitTime = 0;
    private String autoCompleteTextView_str;

    private PopupWindow mPopWindow;
    private View contentView;
    private View rootView;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "Press the exit App again.", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            mPopWindow.dismiss();
            finish();
            System.exit(0);
        }
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.autocomplete_country, R.id.main_setting, R.id.search_img, R.id.delete_text})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.main_setting:

                if (drawerLayout.isDrawerOpen(navigationView)){
                    drawerLayout.closeDrawer(navigationView);
                }else{
                    drawerLayout.openDrawer(navigationView);
                }
                break;
            case R.id.search_img:
                autoCompleteTextView_str = autoCompleteTextView.getText().toString();
                hasSendResult = true;
                break;
            case R.id.delete_text:
                autoCompleteTextView.setText("");
                deleteText.setVisibility(View.GONE);
                break;
        }

    }

    @Override
    public void initView() {
        //侧滑部分
        View headview=navigationView.getHeaderView(0);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.menu_settings_server:
                        Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case R.id.menu_about_version:
                        DownLoadUtils.getInstance().downLoadNewApk("http://gdown.baidu.com/data/wisegame/de18ef5aaf357deb/yingyongbao_7282130.apk", "zhonglianApp");
                        break;

                }
                return true;
            }
        });


        //mPopWindow部分
        rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_list, null);
        searchListview = contentView.findViewById(R.id.search_listview);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, false);
        mPopWindow.setContentView(contentView);
        //历史记录
        historyBeanList = new ArrayList<>();
        couponVPAdapter = new CouponVPAdapter(getSupportFragmentManager());
        vpMain.setOffscreenPageLimit(0);
        vpMain.setAdapter(couponVPAdapter);
        tablayout.setupWithViewPager(vpMain);
        projectDataUtils = new ProjectDataUtils();
        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    //隐藏“删除”图片
                    //显示“删除图片”
                    searchListview.setVisibility(View.GONE);
                    deleteText.setVisibility(View.GONE);
                } else {//长度不为0
                    //显示“删除图片”
                    deleteText.setVisibility(View.VISIBLE);
                    searchListview.setVisibility(View.VISIBLE);
                    //显示ListView
                    if (searchListviewAdapter != null) {
                        searchListviewAdapter.notifyDataSetInvalidated();
                    }
                    showListView();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void showListView() {
        serchallstationlists.clear();
        //用pup
        searchListview.setVisibility(View.VISIBLE);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.showAsDropDown(searchEditLly);
        mPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPopWindow.setTouchable(true);
        mPopWindow.isFocusable();


        //获得输入的内容
        String str = autoCompleteTextView.getText().toString().trim();
        if (SPUtils.getStationString(getContext(), spstationkey) != null && !SPUtils.getStationString(getContext(), spstationkey).equals("")
                && SPUtils.getStationString(getApplicationContext(), splinekey) != null && !SPUtils.getStationString(getApplicationContext(), splinekey).equals("")) {
            allstationlist = projectDataUtils.analyseAllStationName(SPUtils.getStationString(getContext(), spstationkey));
            Log.d("may", "allstationlist-------: " + allstationlist.size());
            List<ServerLineInfo> serverLinelist = projectDataUtils.getAllLineNum(SPUtils.getStationString(getApplicationContext(), splinekey));
            Log.d("may", "serverLinelist-------: " + serverLinelist.size());
            for (int i = 0; i < serverLinelist.size(); i++) {
                if (serverLinelist.get(i).getLineNum().contains(str)) {
                    List<List<StationInfo>> choiceUDStationlist = new ArrayList<>();//注意集合对象要更新
                    choiceUDStationlist = projectDataUtils.getAllChoiceStList(SPUtils.getStationString(getContext(), spstationkey), serverLinelist.get(i).getLineNum());
                    Log.d("may", "choiceUDStationlist-------: " + choiceUDStationlist.size());
                    for (int j = 0; j < choiceUDStationlist.size(); j++) {
                        if (choiceUDStationlist.get(j) != null && choiceUDStationlist.get(j).size() != 0) {//线路不为空添加到集合
                            Log.d("may", "choiceUDStationlist.get-------: " + choiceUDStationlist.get(j).size());
                            serchallstationlists.add(choiceUDStationlist.get(j));
                        }
                    }
                }
            }
            Log.d("may", "serchallstationlists-------: " + serchallstationlists.size());
            if (serchallstationlists.size() != 0 && serchallstationlists != null) {

                searchListviewAdapter = new SearchListviewAdapter(serchallstationlists, getApplicationContext());
                searchListview.setAdapter(searchListviewAdapter);
                searchListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        SearchCarlineMssEvent searchCarlineMssEvent = new SearchCarlineMssEvent();
                        searchCarlineMssEvent.setIsupline(serchallstationlists.get(position).get(0).getIsupline());
                        searchCarlineMssEvent.setLineNum(serchallstationlists.get(position).get(0).getLineNum());
                        searchCarlineMssEvent.setLineStart(serchallstationlists.get(position).get(0).getStationName());
                        searchCarlineMssEvent.setLineEnd(serchallstationlists.get(position).get(serchallstationlists.get(position).size() - 1).getStationName());
                        EventBus.getDefault().postSticky(searchCarlineMssEvent);
                        //设置历史记录
                        if (SPUtils.getArray(getContext(), SPUtils.HISTORYLIST, HistoryBean.class) != null) {
                            historyBeanList = SPUtils.getArray(MainActivity.this, SPUtils.HISTORYLIST, HistoryBean.class);
                        }
                        HistoryBean bean = new HistoryBean();
                        bean.setLineNum(serchallstationlists.get(position).get(0).getLineNum());
                        bean.setIsupline(serchallstationlists.get(position).get(0).getIsupline());
                        String strBean = serchallstationlists.get(position).get(0).getLineNum() + "(" + serchallstationlists.get(position).get(0).getStationName() + "--->" + serchallstationlists.get(position).get(serchallstationlists.get(position).size() - 1).getStationName() + ")";
                        bean.setName(strBean);
                        historyBeanList.add(0, bean);

                        //去重
                        for (int i = 0; i < historyBeanList.size() - 1; i++) {
                            for (int j = i + 1; j < historyBeanList.size(); j++) {
                                if (historyBeanList.get(i).getName().equals(historyBeanList.get(j).getName())) {
                                    historyBeanList.remove(historyBeanList.get(j));
                                    j--;
                                }
                            }
                        }
                        SPUtils.removeArray(MainActivity.this, SPUtils.HISTORYLIST);
                        SPUtils.setArray(MainActivity.this, SPUtils.HISTORYLIST, historyBeanList);
                        Intent intent = new Intent(MainActivity.this, BusRunActivity.class);
                        startActivity(intent);
                        mPopWindow.dismiss();
                        MainActivity.this.finish();

                    }
                });
                //判断serchallstationlists集合是否为空

            } else {

                handler.sendEmptyMessage(1);//没有线路信息是时提示
            }

        }//保护


    }

    @Override
    public void initData() {
        hasSendResult = true;
        SPUtils.setStationString(getContext(), spstationkey, "");
        SPUtils.setStationString(getContext(), splinekey, "");
        result_lineinfo = null;
    }

    //test

    public void insertDateSql() {
        stationlist = projectDataUtils.analyseAllStationName(SPUtils.getStationString(getContext(), spstationkey));
        DbStationInfo dbStationInfo = new DbStationInfo(getContentResolver(), this);
        dbStationInfo.deleteAllStationInfo();
        for (int i = 0; i < stationlist.size(); i++) {
            dbStationInfo.InsertAllStaInfo(stationlist.get(i));
        }
    }
    //线程

    public class MyThread extends Thread {

        public void run() {
            Log.d("may", "hasSendResult: " + hasSendResult);
            while (hasSendResult) {
                //重新运用模糊搜索
                if ((!SPUtils.getConfigserverString(getContext(), "server").equals("")) && (!SPUtils.getConfigserverString(getContext(), "port").equals("")) && (!SPUtils.getConfigserverString(getContext(), "subserver").equals(""))) {
                    String server = "http://" + SPUtils.getConfigserverString(getContext(), "server") + ":" + SPUtils.getConfigserverString(getContext(), "port") + "/" + SPUtils.getConfigserverString(getContext(), "subserver") + "/";
                    String pathline = "GetLineInfos";
                    result_lineServer = projectDataUtils.httpGet(server, pathline, null, null);
                    String path = "station/station" + ".txt";
                    result_lineinfo = projectDataUtils.httpGet(server, path, null, null);
                } else {
                    //String server = "http://203.245.9.76:10085/Busyingni/";
                    String server = "http://122.112.241.174:10085/Busyingni/";
                    String pathline = "GetLineInfos";
                    result_lineServer = projectDataUtils.httpGet(server, pathline, null, null);
                    String path = "station/station" + ".txt";
                    result_lineinfo = projectDataUtils.httpGet(server, path, null, null);
                    Log.d("may", "fff:222server" + server + path);
                }
                //Log.d("may", "fff:result_lineinfo" + result_lineinfo);

                handler.sendEmptyMessage(0);
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        new MyThread().start();
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        if (result_lineinfo != null && (!result_lineinfo.equals("")) && result_lineServer != null && (!result_lineinfo.equals(""))) {
                            SPUtils.setStationString(getContext(), splinekey, result_lineServer);
                            SPUtils.setStationString(getContext(), spstationkey, result_lineinfo);
                            hasSendResult = false;
                        }

                        break;
                    case 1:
                        Toast toast = Toast.makeText(getContext(), "No relevant line information, please re-enter.", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.TOP, 0, 250);
                        toast.show();
                        //解决模糊搜索问题出现listview 刷新bug

                        break;
                    case 2:

                        break;
                }
            }
        };

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hasSendResult = false;
    }
}
